<template>
  <Teleport to="body">
    <div
      class="top-0 left-0 z-50 fixed"
      :class="[
        { ContactDetailDialog: !isMobileOrTablet },
        { 'top-1/4 left-1/3': isMobileOrTablet }
      ]"
    >
      <div
        v-if="pendingUserInfo"
        class="select-none px-3 pt-7 pb-4 w-[586px] h-[600px] relative flex items-center justify-center bg-c-white shadow-popup-l rounded-xl"
      >
        <AtomSpinner110 />
      </div>
      <div
        v-else
        class="select-none px-3 pt-7 pb-4 w-[586px] flex relative flex-col gap-5 bg-c-white shadow-popup-l"
        :class="[
          { 'rounded-xl': historyStack.length <= 1 },
          {
            'rounded-es-lg rounded-ee-lg rounded-se-lg': historyStack.length > 1
          }
        ]"
      >
        <div
          v-if="historyStack.length > 1"
          class="absolute rounded-ss-lg border-c-grey-xs border-r-2 rounded-es-lg flex items-center justify-center h-12 w-7 top-0 -left-[28px] bg-c-white"
          @click="backByHistory"
        >
          <SvgoArrow
            class="scale-150 rotate-90 cursor-pointer text-c-grey-medium hover:text-c-grey-large"
            filled
          />
        </div>
        <div class="flex items-center">
          <div class="ml-2 mr-8">
            <img
              v-if="userPhotoComputedSrc && !pendingUserPhoto"
              :src="userPhotoComputedSrc"
              class="h-[120px] w-[120px] rounded-full"
            />
            <Skeletor v-else-if="pendingUserPhoto" circle size="120" />
            <SvgoErrAva
              v-else
              class="h-[120px] w-[120px]"
              :font-controlled="false"
              filled
            />
          </div>
          <div class="flex flex-col gap-3">
            <div class="flex gap-[22px] items-center">
              <p class="heading-xl-semi text-c-grey-3xl">
                {{
                  (userInfo?.lastNameRu ?? '-') +
                  ' ' +
                  (userInfo?.firstNameRu ?? '-')
                }}
              </p>
              <div class="flex gap-4">
                <div class="relative">
                  <div
                    v-if="!userStore.getIsFavorite(currentContactId as string)"
                    ref="hoverFavoriteDisableIcon"
                  >
                    <SvgoStarDisabled
                      class="scale-125 cursor-pointer text-c-grey-medium hover:text-c-grey-large"
                      filled
                      @click.stop="toFavorites"
                    />
                  </div>
                  <div
                    v-if="userStore.getIsFavorite(currentContactId as string)"
                    ref="hoverFavoriteEnableIcon"
                  >
                    <SvgoStarEnabled
                      class="cursor-pointer scale-125"
                      filled
                      @click.stop="toFavorites"
                    />
                  </div>
                  <AtomTooltip
                    v-if="
                      (isHoveredFavoriteDisableIcon &&
                        hoverFavoriteDisableIcon) ||
                      (isHoveredFavoriteEnableIcon && hoverFavoriteEnableIcon)
                    "
                    class="absolute z-50 top-5 -left-[75px]"
                    arrow-position="up"
                    :text="!userStore.getIsFavorite(currentContactId as string) ? 'Добавить в избранные' : 'Удалить из избранных'"
                  />
                </div>
                <div class="relative">
                  <SvgoLink
                    ref="hoverLinkIcon"
                    class="scale-125 cursor-pointer text-c-grey-medium hover:text-c-grey-large"
                    filled
                    @click="copyContactLink"
                  />
                  <AtomTooltip
                    v-if="isHoveredLinkIcon"
                    class="absolute z-50 top-5 -left-[110px]"
                    arrow-position="up"
                    text="Скопировать ссылку на контакт"
                  />
                </div>
              </div>
            </div>
            <div class="flex gap-3 mr-11">
              <AtomButton
                class="flex-2"
                label="Написать письмо"
                @click="handleMailTo"
              >
                <template #prefix-icon>
                  <SvgoLetter class="scale-150" filled />
                </template>
              </AtomButton>
              <AtomButton class="flex-1" label="Чат" @click="handleChatTo">
                <template #prefix-icon>
                  <SvgoMessage class="scale-150" filled />
                </template>
              </AtomButton>
            </div>
          </div>
          <SvgoCloseIcon
            class="cursor-pointer scale-150 text-c-grey-medium hover:text-c-grey-large self-start"
            filled
            @click="$router.push({ query: {} })"
          />
        </div>
        <AtomHorizontalDivider />
        <div class="grid grid-cols-contact-info px-3 gap-y-3">
          <div class="heading-m-medium text-c-grey-xl">Email:</div>
          <div class="flex items-center gap-4">
            <div ref="hoverEmail" class="heading-m-medium text-c-grey-3xl">
              {{ userInfo?.email ?? '-' }}
            </div>
            <div class="relative">
              <SvgoCopy
                v-if="isHoveredEmail || isHoveredCopyEmailIcon"
                ref="hoverCopyEmailIcon"
                class="cursor-pointer scale-125 text-c-grey-medium stroke-grey-medium hover:text-c-grey-large hover:stroke-grey-large"
                filled
                @click="copyEmail"
              />
              <AtomTooltip
                v-if="isHoveredCopyEmailIcon"
                class="absolute z-50 -top-1.5 left-6"
                text="Скопировать"
              />
            </div>
          </div>
          <div class="heading-m-medium text-c-grey-xl">Телефон:</div>
          <div class="flex items-center gap-4">
            <div ref="hoverTel" class="heading-m-medium text-c-grey-3xl">
              {{ userInfo?.phone ?? '-' }}
            </div>
            <div class="relative">
              <SvgoCopy
                v-if="isHoveredTel || isHoveredCopyTelIcon"
                ref="hoverCopyTelIcon"
                class="cursor-pointer scale-125 text-c-grey-medium stroke-grey-medium hover:text-c-grey-large hover:stroke-grey-large"
                filled
                @click="copyTel"
              />
              <AtomTooltip
                v-if="isHoveredCopyTelIcon"
                class="absolute z-50 -top-1.5 left-6"
                text="Скопировать"
              />
            </div>
          </div>
          <div class="heading-m-medium text-c-grey-xl">Дата рождения:</div>
          <div class="heading-m-medium text-c-grey-3xl">
            {{ userInfo?.birthDate ? useDateFormat(userInfo?.birthDate) : '-' }}
          </div>
          <div class="heading-m-medium text-c-grey-xl">Город:</div>
          <div class="heading-m-medium text-c-grey-3xl">
            {{ userInfo?.cityRu ?? '-' }}
          </div>
          <div
            v-if="userInfo?.workplace"
            class="heading-m-medium text-c-grey-xl"
          >
            Рабочее место:
          </div>
          <div
            v-if="userInfo?.workplace"
            class="heading-m-medium text-c-grey-3xl"
          >
            {{ userInfo?.workplace ?? '-' }}
          </div>
        </div>
        <AtomHorizontalDivider />
        <div class="grid grid-cols-contact-info px-3 gap-y-3">
          <div class="heading-m-medium text-c-grey-xl">Организация:</div>
          <div class="heading-m-medium text-c-grey-3xl">
            {{ userInfo?.orgNameRu ?? '-' }}
          </div>
          <div class="heading-m-medium text-c-grey-xl">Должность:</div>
          <div class="heading-m-medium text-c-grey-3xl">
            {{ userInfo?.positionNameRu ?? '-' }}
          </div>
          <div class="heading-m-medium text-c-grey-xl">Отдел:</div>
          <div class="heading-m-medium text-c-grey-3xl">
            {{ userInfo?.unitNameRu ?? '-' }}
          </div>
        </div>
        <AtomHorizontalDivider />
        <div class="grid grid-cols-contact-info px-3">
          <div class="heading-m-medium text-c-grey-xl">Руководитель:</div>
          <div
            class="flex gap-3 px-3 py-3 rounded-xl -mt-2 -ml-3 max-w-[335px]"
            :class="[
              {
                'hover:bg-c-grey-xs': computedHead1InfoBlock
              },
              {
                'cursor-pointer': computedHead1InfoBlock
              }
            ]"
            @click="showHeadInfo"
          >
            <img
              v-if="head1PhotoComputedSrc && !pendingHead1Photo"
              :src="head1PhotoComputedSrc"
              class="w-[42px] h-[42px] rounded-full"
            />
            <Skeletor v-else-if="pendingHead1Photo" circle size="42" />
            <SvgoErrAva
              v-else
              filled
              :font-controlled="false"
              class="h-[42px] w-[42px]"
            />
            <div class="flex flex-col">
              <p class="heading-m-medium text-c-grey-3xl">
                {{
                  computedHead1InfoBlock
                    ? userInfo?.head1LastNameRu +
                      ' ' +
                      userInfo?.head1FirstNameRu
                    : 'Нет данных'
                }}
              </p>
              <p class="paragraph-s-medium text-c-grey-xl">
                {{ userInfo?.head1PositionNameRu ?? '-' }}
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </Teleport>
</template>

<script setup lang="ts">
import { useNotificationStore } from '~/stores/notificationStore'
import { useUserStore } from '~/stores/userStore'
import { ApiEndpoints } from '~/types/ApiEndpoints'
import type { IUser } from '~/types/User'
const route = useRoute()
const router = useRouter()
const { copy } = useClipboard()
const historyStack = reactive([])
const userStore = useUserStore()
const notificationStore = useNotificationStore()

const hoverTel: Ref<null | HTMLElement> = ref(null)
const hoverEmail: Ref<null | HTMLElement> = ref(null)
const hoverCopyTelIcon: Ref<null | HTMLElement> = ref(null)
const hoverCopyEmailIcon: Ref<null | HTMLElement> = ref(null)
const hoverFavoriteDisableIcon: Ref<null | HTMLElement> = ref(null)
const hoverFavoriteEnableIcon: Ref<null | HTMLElement> = ref(null)
const hoverLinkIcon: Ref<null | HTMLElement> = ref(null)

const isHoveredTel = useElementHover(hoverTel, { delayLeave: 400 })
const isHoveredEmail = useElementHover(hoverEmail, { delayLeave: 400 })
const isHoveredCopyTelIcon = useElementHover(hoverCopyTelIcon)
const isHoveredCopyEmailIcon = useElementHover(hoverCopyEmailIcon)
const isHoveredFavoriteDisableIcon = useElementHover(hoverFavoriteDisableIcon)
const isHoveredFavoriteEnableIcon = useElementHover(hoverFavoriteEnableIcon)
const isHoveredLinkIcon = useElementHover(hoverLinkIcon)

const { isMobileOrTablet } = useDevice()

const currentContactId = computed(() => {
  return route.query.contactId
})

// get user immediatly after mount
const { data: userInfo, pending: pendingUserInfo } =
  await useAPILazyFetch<IUser>(ApiEndpoints.GET_USER_BY_ID, {
    query: { contactId: currentContactId }
  })
// get user photo immediatly after mount
const { data: userPhoto, pending: pendingUserPhoto } = await useAPILazyFetch(
  ApiEndpoints.GET_USER_PHOTO,
  {
    query: { contactId: currentContactId }
  }
)

const computedHead1Id = computed(() => {
  return useUnProxy(userInfo)?.head1Id || ''
})

// get head1Photo if userInfo changes
const { data: head1Photo, pending: pendingHead1Photo } = await useAPILazyFetch(
  ApiEndpoints.GET_USER_PHOTO,
  {
    immediate: false,
    query: { contactId: computedHead1Id }
  }
)
const userPhotoComputedSrc = computed(() => {
  if (userPhoto.value) {
    return useBufferToImgSrc(useUnProxy(userPhoto)?.data)
  }
  return null
})

const head1PhotoComputedSrc = computed(() => {
  if (head1Photo.value) {
    return useBufferToImgSrc(useUnProxy(head1Photo)?.data)
  }
  return null
})

const handleMailTo = () => {
  if (userInfo.value?.email) {
    window.open(`mailto:${userInfo?.value.email}`)
  }
}

const computedHead1InfoBlock = computed(
  () =>
    userInfo.value?.head1LastNameRu &&
    userInfo.value?.head1FirstNameRu &&
    userInfo.value?.head1PositionNameRu
)

const handleChatTo = () => {
  if (userInfo.value?.email) {
    window.open(
      `https://teams.microsoft.com/l/chat/0/0?users=${userInfo?.value.email}`
    )
  }
}

const showHeadInfo = () => {
  if (userInfo.value.head1Id) {
    router.push({ query: { contactId: userInfo.value.head1Id } })
    historyStack.push(userInfo.value.head1Id)
  }
}

const copyContactLink = () => {
  let url = window.location.href.toString()
  // bugfix PP-81
  if (url.includes('favorites')) {
    url = window.location.origin + '/?' + url.split('?')[1]
  }
  copy(url)
  notificationStore.showNotification('Ссылка на контакт скопирована')
}

const copyEmail = () => {
  copy(userInfo.value.email)
  notificationStore.showNotification('Скопировано')
}

const copyTel = () => {
  copy(userInfo.value.phone)
  notificationStore.showNotification('Скопировано')
}

const toFavorites = async () => {
  userStore.changeFavorites(currentContactId.value as string)
  const { error } = await useAPIFetch(ApiEndpoints.SET_FAVORITE, {
    method: 'PUT',
    body: {
      userId: userStore.user.id,
      favoriteId: currentContactId.value as string
    }
  })
  if (error.value) {
    console.error(error.value.message)
  }
}

const backByHistory = () => {
  historyStack.pop()
  router.back()
}

onBeforeMount(() => {
  historyStack.push(route.query.contactId)
})
</script>

<style scoped lang="scss">
$component: '.ContactDetailDialog';

#{$component} {
  transform: translate(calc(50vw - 50%), calc(50vh - 50%));
}
</style>
